<template>
  <div class="auto-bid-manage">
    <el-card>
      <template #header>
        <div class="page-header">
          <div class="header-left">
            <h2 class="page-title">
              <el-icon><Setting /></el-icon>
              自动出价管理
            </h2>
            <p class="page-desc">管理会员的自动出价配置和统计信息</p>
          </div>
          <div class="header-right">
            <el-button type="primary" @click="showCreateDialog">
              <el-icon><Plus /></el-icon>
              新增配置
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索和筛选 -->
      <div class="search-section">
        <el-row :gutter="16">
          <el-col :span="6">
            <el-input
              v-model="searchForm.keyword"
              placeholder="搜索会员ID、昵称或手机号"
              clearable
              @input="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </el-col>
          <el-col :span="4">
            <el-select v-model="searchForm.level" placeholder="会员等级" clearable @change="handleSearch">
              <el-option v-for="level in allLevels" :key="level" :label="level" :value="level" />
            </el-select>
          </el-col>
          <el-col :span="4">
            <el-select v-model="searchForm.status" placeholder="配置状态" clearable @change="handleSearch">
              <el-option label="已配置" value="configured" />
              <el-option label="未配置" value="unconfigured" />
              <el-option label="已启用" value="enabled" />
              <el-option label="已停用" value="disabled" />
            </el-select>
          </el-col>
          <el-col :span="4">
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
          </el-col>
        </el-row>
      </div>

      <!-- 统计卡片 -->
      <div class="stats-section">
        <el-row :gutter="16">
          <el-col :span="6">
            <div class="stat-card">
              <div class="stat-icon">
                <el-icon><User /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-value">{{ stats.totalMembers }}</div>
                <div class="stat-label">总会员数</div>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-card">
              <div class="stat-icon success">
                <el-icon><Check /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-value">{{ stats.configuredMembers }}</div>
                <div class="stat-label">已配置</div>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-card">
              <div class="stat-icon primary">
                <el-icon><TrendCharts /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-value">{{ stats.enabledMembers }}</div>
                <div class="stat-label">已启用</div>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-card">
              <div class="stat-icon warning">
                <el-icon><Clock /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-value">{{ stats.todayBids }}</div>
                <div class="stat-label">今日出价</div>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>

      <!-- 会员列表 -->
      <div class="table-section">
        <el-table :data="filteredMembers" style="width: 100%" v-loading="loading">
          <el-table-column prop="id" label="会员ID" width="120" />
          <el-table-column prop="nickname" label="昵称" width="150">
            <template #default="{ row }">
              <div class="member-info">
                <el-avatar :src="getCustomerAvatar(row.id)" :size="32">
                  {{ getCustomerInitials(row.nickname) }}
                </el-avatar>
                <span class="member-name">{{ row.nickname || '未知用户' }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="phone" label="手机号" width="130" />
          <el-table-column prop="level" label="等级" width="80">
            <template #default="{ row }">
              <el-tag :type="getLevelTagType(row.level)" size="small">
                {{ row.level || 'L1' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="配置状态" width="120">
            <template #default="{ row }">
              <el-tag 
                :type="getConfigStatusType(row.configStatus)" 
                size="small"
              >
                {{ getConfigStatusText(row.configStatus) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="启用状态" width="120">
            <template #default="{ row }">
              <el-switch 
                v-model="row.enabled" 
                @change="handleEnableChange(row)"
                :disabled="!row.configStatus"
              />
            </template>
          </el-table-column>
          <el-table-column label="账号数量" width="100">
            <template #default="{ row }">
              <span v-if="row.configStatus">{{ row.accountCount || 0 }} 个</span>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column label="今日出价" width="120">
            <template #default="{ row }">
              <span v-if="row.todayBids">{{ row.todayBids }} 次</span>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-button 
                size="small" 
                type="primary" 
                @click="openConfigDialog(row)"
              >
                配置
              </el-button>
              <el-button 
                size="small" 
                type="info" 
                @click="openStatsDialog(row)"
                :disabled="!row.configStatus"
              >
                统计
              </el-button>
              <el-button 
                size="small" 
                type="warning" 
                @click="testConfig(row)"
                :disabled="!row.configStatus"
              >
                测试
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="filteredMembers.length"
            layout="total, sizes, prev, pager, next, jumper"
          />
        </div>
      </div>
    </el-card>

    <!-- 配置弹窗 -->
    <AutoBidConfig 
      v-model="showConfigDialog"
      :member="selectedMember"
      @save="handleConfigSave"
    />

    <!-- 统计弹窗 -->
    <el-dialog v-model="showStatsDialog" title="自动出价统计" width="800px">
      <AutoBidStats 
        v-if="selectedMember"
        :member-id="selectedMember.id"
        :accounts="selectedMember.accounts"
      />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Setting, Plus, Search, User, Check, TrendCharts, Clock } from '@element-plus/icons-vue'
import AutoBidConfig from '@/components/AutoBidConfig.vue'
import AutoBidStats from '@/components/AutoBidStats.vue'
import { autoBidService } from '@/services/autoBidService'

interface Member {
  id: string
  nickname?: string
  phone?: string
  level?: string
  configStatus?: string
  enabled?: boolean
  accountCount?: number
  todayBids?: number
  accounts?: any[]
}

const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(20)

const allLevels = ['L1', 'L2', 'L3', 'L4', 'L5', 'L6', 'L7']

const searchForm = reactive({
  keyword: '',
  level: '',
  status: ''
})

const stats = reactive({
  totalMembers: 0,
  configuredMembers: 0,
  enabledMembers: 0,
  todayBids: 0
})

const members = ref<Member[]>([])
const selectedMember = ref<Member | null>(null)
const showConfigDialog = ref(false)
const showStatsDialog = ref(false)

const filteredMembers = computed(() => {
  let filtered = members.value

  if (searchForm.keyword) {
    const keyword = searchForm.keyword.toLowerCase()
    filtered = filtered.filter(member => 
      member.id.toLowerCase().includes(keyword) ||
      member.nickname?.toLowerCase().includes(keyword) ||
      member.phone?.includes(keyword)
    )
  }

  if (searchForm.level) {
    filtered = filtered.filter(member => member.level === searchForm.level)
  }

  if (searchForm.status) {
    filtered = filtered.filter(member => {
      switch (searchForm.status) {
        case 'configured':
          return member.configStatus === 'configured'
                 case 'unconfigured':
           return member.configStatus === undefined || member.configStatus === null
        case 'enabled':
          return member.enabled
        case 'disabled':
          return member.configStatus && !member.enabled
        default:
          return true
      }
    })
  }

  return filtered
})

async function loadMembers() {
  loading.value = true
  try {
    // 模拟从API获取会员数据
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    members.value = [
      {
        id: 'M001',
        nickname: '张三',
        phone: '13800138001',
        level: 'L3',
        configStatus: 'configured',
        enabled: true,
        accountCount: 3,
        todayBids: 5
      },
      {
        id: 'M002',
        nickname: '李四',
        phone: '13800138002',
        level: 'L5',
        configStatus: 'configured',
        enabled: false,
        accountCount: 2,
        todayBids: 0
      },
      {
        id: 'M003',
        nickname: '王五',
        phone: '13800138003',
        level: 'L2',
        configStatus: null,
        enabled: false,
        accountCount: 0,
        todayBids: 0
      }
    ]

    // 更新统计数据
    updateStats()
  } catch (error) {
    console.error('加载会员数据失败:', error)
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

function updateStats() {
  stats.totalMembers = members.value.length
  stats.configuredMembers = members.value.filter(m => m.configStatus).length
  stats.enabledMembers = members.value.filter(m => m.enabled).length
  stats.todayBids = members.value.reduce((sum, m) => sum + (m.todayBids || 0), 0)
}

function handleSearch() {
  currentPage.value = 1
}

function showCreateDialog() {
  selectedMember.value = {
    id: '',
    nickname: '',
    phone: '',
    level: 'L1'
  }
  showConfigDialog.value = true
}

function openConfigDialog(member: Member) {
  selectedMember.value = member
  showConfigDialog.value = true
}

function openStatsDialog(member: Member) {
  selectedMember.value = member
  showStatsDialog.value = true
}

async function handleConfigSave(config: any) {
  if (selectedMember.value) {
    // 更新会员配置状态
    selectedMember.value.configStatus = 'configured'
    selectedMember.value.enabled = config.enabled
    selectedMember.value.accountCount = config.accounts.length
    
    updateStats()
    ElMessage.success('配置保存成功')
  }
}

async function handleEnableChange(member: Member) {
  try {
    await ElMessageBox.confirm(
      `确定要${member.enabled ? '启用' : '停用'}该会员的自动出价功能吗？`,
      '确认操作',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    updateStats()
    ElMessage.success(`${member.enabled ? '启用' : '停用'}成功`)
  } catch {
    // 用户取消操作，恢复状态
    member.enabled = !member.enabled
  }
}

async function testConfig(member: Member) {
  try {
    ElMessage.info('正在测试配置...')
    const result = await autoBidService.testAutoBidConfig(member.id, {
      enabled: true,
      accounts: []
    })
    
    if (result.success) {
      ElMessage.success('测试成功，配置有效')
    } else {
      ElMessage.warning('测试失败，请检查配置')
    }
  } catch (error) {
    ElMessage.error('测试失败，请重试')
  }
}

function getCustomerAvatar(customerId: string) {
  return `https://api.dicebear.com/7.x/avataaars/svg?seed=${customerId}`
}

function getCustomerInitials(nickname: string) {
  if (!nickname) return 'U'
  return nickname.substring(0, 2).toUpperCase()
}

function getLevelTagType(level: string) {
  const levelMap: Record<string, string> = {
    'L1': 'info',
    'L2': 'success',
    'L3': 'warning',
    'L4': 'danger',
    'L5': 'danger',
    'L6': 'danger',
    'L7': 'danger'
  }
  return levelMap[level] || 'info'
}

function getConfigStatusType(status: string | undefined) {
  if (!status) return 'info'
  return 'success'
}

function getConfigStatusText(status: string | undefined) {
  if (!status) return '未配置'
  return '已配置'
}

onMounted(() => {
  loadMembers()
})
</script>

<style scoped>
.auto-bid-manage {
  padding: 24px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.header-left {
  .page-title {
    margin: 0 0 8px 0;
    font-size: 20px;
    font-weight: 600;
    color: #303133;
    display: flex;
    align-items: center;
    gap: 8px;
  }
  
  .page-desc {
    margin: 0;
    color: #909399;
    font-size: 14px;
  }
}

.search-section {
  margin-bottom: 24px;
  padding: 16px;
  background: #f5f7fa;
  border-radius: 8px;
}

.stats-section {
  margin-bottom: 24px;
}

.stat-card {
  display: flex;
  align-items: center;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s;
  
  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  }
  
  .stat-icon {
    width: 48px;
    height: 48px;
    border-radius: 8px;
    background: #409eff;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 16px;
    
    &.success {
      background: #67c23a;
    }
    
    &.primary {
      background: #409eff;
    }
    
    &.warning {
      background: #e6a23c;
    }
    
    .el-icon {
      font-size: 24px;
      color: #fff;
    }
  }
  
  .stat-content {
    flex: 1;
  }
  
  .stat-value {
    font-size: 24px;
    font-weight: 700;
    color: #303133;
    margin-bottom: 4px;
  }
  
  .stat-label {
    font-size: 12px;
    color: #909399;
  }
}

.table-section {
  .member-info {
    display: flex;
    align-items: center;
    gap: 8px;
  }
  
  .member-name {
    font-size: 14px;
    color: #303133;
  }
  
  .pagination-wrapper {
    margin-top: 16px;
    text-align: right;
  }
}
</style> 